package sql

import (
	"context"
	"log"

	"gitee.com/go-errors/errors"
	"gitee.com/go-wena/app/internal/sql/internal"
	"gitee.com/go-wena/env"

	"gorm.io/gorm"
)

var defaultInstance, _ = gorm.Open(nil)

func init() {
	defaultInstance.Error = errors.New("sql: not init")
}

func Auto() {
	if !env.GetBool("sql.enabled") {
		defaultInstance, _ = gorm.Open(nil)
		defaultInstance.Error = errors.New("sql: disabled")
		log.Printf("%v\n", defaultInstance.Error)
		return
	}

	dsn := env.GetString("sql.dsn")
	log.Printf("sql: connect: %s\n", dsn)

	defaultInstance = internal.New(dsn)
	if err := Ping(context.Background()); err != nil {
		log.Printf("sql: ping: %v\n", err)
	}
}
